<!--新的页面-->
<template>
  <div>
    <table-ext :columns="columns" :searchForm="searchForm" :config="config" ref="tableExt">
      <template slot="form-action">
         <el-button type="primary" @click="roleAdd">新增</el-button>
      </template>
    </table-ext>
    <el-dialog :title="roleEditDialog.isRoleAdding?'角色新增':'角色编辑'" :visible.sync="roleEditDialog.visible"  width="70%">
      <el-form :inline="true" :model="roleEditDialog" :rules="roleDialogRules" ref="roleDialogRuleForm" class="demo-form-inline" v-if="roleEditDialog.isRoleAdding">
        <el-form-item label="角色编码" prop="roleData.code">
          <el-input v-model="roleEditDialog.roleData.code" placeholder="code"></el-input>
        </el-form-item>
        <el-form-item label="角色名称">
          <el-input v-model="roleEditDialog.roleData.description" placeholder="description"></el-input>
        </el-form-item>
      </el-form>
      <el-tabs v-model="roleEditDialog.tabs.active" v-loading="roleEditDialog.loading" type="card" id="roleTabs">
        <el-tab-pane label="采购商" name="purchaser">
          <div style="max-height: 480px; overflow: auto">
            <el-tree
              :data="purchaserTreeData"
              ref="purchaserTree"
              class="purchaserTree"
              @check="roleDialogPurchaserTreeCheck"
              show-checkbox
              node-key="id"
              :check-strictly="true"
              :default-checked-keys="purchaserTreeCheckedKey">
              <span slot-scope="{ node, data }">
                <operate-check :nodeData="node.data" @check-change="purchaserOperateCheckChange" :ref="'purchaserTree-' + node.data.id"></operate-check>
              </span>
            </el-tree>
          </div>
        </el-tab-pane>
        <el-tab-pane label="供应商" name="supplier">
          <div style="max-height: 480px; overflow: auto">
            <el-tree
              :data="supplierTreeData"
              ref="supplierTree"
              class="supplierTree"
              @check="roleDialogSupplierTreeCheck"
              show-checkbox
              node-key="id"
              :check-strictly="true"
              :default-checked-keys="supplierTreeCheckedKey">
              <span slot-scope="{ node, data }">
                <operate-check :nodeData="node.data" @check-change="supplierOperateCheckChange" :ref="'supplierTree-' + node.data.id"></operate-check>
              </span>
            </el-tree>
          </div>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleEditDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="roleCommit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="分配用户" :visible.sync="dialogAllowUserVisible" :close-on-click-modal="false" :show-close="false" width="800px">
      <el-form :model="userform">
        <el-input v-if='isShow' v-model="userform.roleId"></el-input>
        <template>

          <div style="text-align: center">
            <!-- <el-transfer style="text-align: left; display: inline-block" v-model="userform.userIdss" filterable
                         :render-content="renderFunc"
                         :titles="['可选用户', '已选用户']" :button-texts="['到左边', '到右边']" :format="{
        noChecked: '${total}',
        hasChecked: '${checked}/${total}'
      }" :data="userData">
            </el-transfer> -->
            <vendors-transfer ref="trans"
                width="100%" :checkName="['account','name']"
                 :title="{left:'可选用户',right:'已选用户'}"
                 :searchForm="searchUserForm"
                 :selectData="userform.userIdss" :isQsparams = false
                :url="this.lib.config.host.system + '/system/usermgt/users/query'">
                </vendors-transfer>
          </div>

        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resrRoleForm">取 消</el-button>
        <el-button type="primary" @click="allowRole(userform)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
  import TableExt from '@/components/common/table-ext/table-ext.vue';
  import qs from 'qs';
  import ElDialog from "../../../../node_modules/element-ui/packages/dialog/src/component.vue";
  import { Loading } from 'element-ui';
  import { Message } from 'element-ui';
  import OperateCheck from './operate';
  import vendorsTransfer from '@/components/common/select-ext/vendorsTransfer.vue';
  export default {
    // 引入自定义表格组件
    components: {
      ElDialog,
      'table-ext': TableExt,
        vendorsTransfer,
      OperateCheck
    },
    created: function () {

    },
    data() {
      return {
        isShow: false,
        dialogAllowUserVisible: false,
        searchUserForm :[
          // {key:'id',type : '',placeholder:'',value:''}
        ],
        roleEditDialog: {
          visible: false,
          loading: true,
          isRoleAdding: false,
          roleData: {},
//          treeCheckedKey: ['001'],
          tabs: {
            active: ''
          },
//          tree: {
//            data: [],
//            operateCheckList: {}
//          },
          purchaserTree: {
            data: [],
            operateCheckList: {}
          },
          purchaserTreeCheckedKey: [],
          supplierTree: {
            data: [],
            operateCheckList: {}
          },
          supplierTreeCheckedKey: [],
        },
        roleDialogRules:{
          'roleData.code': [
            { required: true, message: '请输入角色编码', trigger: 'blur' }
          ],
        },
        formInline: {},
        userData: [],
        userform: {
          userIdss: [],
          users: ''
        },
        config: { // 页面共通配置
          title: '角色列表', //页面标题
          isPage: true, //是否分页
          isNo: false, //是否显示序号
          selection: false, //是否显示复选框
          crudMapping: { // CRUD方法
            query: {
              url: this.lib.config.host.system + '/system/rolemgt/roles/query',
            }
          }
        },
        // 查询表单配置
        searchForm: [{
          //显示标签
          label: '角色编码',
          //数据字段
          key: 'code',
          //标签类型
          type: 'input'
        }, {
          label: '角色名称',
          key: 'description',
          type: 'input'
        }],

        // 表格列定义
        columns: [{
          label: '操作', // 表格header
          render: (createElement, params) => { // 动态渲染，click事件示例
            let _this = this;
            return createElement('div', {},
              [
                //createElement('el-button', {
                //     props: {
                //       type: 'text',
                //     },
                //     on: {
                //       click() {
                //         //方法待定

                //       }
                //     }
                //   }, '编辑'),
                createElement('el-button', {
                  props: {
                    type: 'text',
                  },
                  on: {
                    click() {
                      //方法待定
                      _this.allowRoleUser(params.row.id);
                    }
                  }
                }, '用户设置'),
                createElement('el-button', {
                  props: {
                    type: 'text',
                  },
                  on: {
                    click() {
                      _this.deleteRole(params.row.id);
                    }
                  }
                }, '删除'),
                createElement('el-button', {
                  props: {
                    type: 'text',
                  },
                  on: {
                    click() {
                      _this.roleEdit(params.row);
                    }
                  }
                }, '编辑')
              ]);
          }
        }, {
          label: '角色编码',
          key: 'code'
        }, {
          label: '角色名称',
          key: 'description'
        }, {
          label: '创建日期',
          key: 'createTime'
        }]
      };
    },
    computed: {
      purchaserTreeData: function () {
        return this.transformToTreeFormat(this.roleEditDialog.purchaserTree.data)
      },
      supplierTreeData: function () {
        return this.transformToTreeFormat(this.roleEditDialog.supplierTree.data)
      },
      purchaserTreeCheckedKey: function () {
        let treeCheckedList=[];
        let data = this.roleEditDialog.purchaserTree.data;
        for (let i=0; i<data.length; i++){
          if (data[i].checked){
            treeCheckedList.push(data[i].id)
          }
        }
        return treeCheckedList
      },
      supplierTreeCheckedKey: function () {
        let treeCheckedList=[];
        let data = this.roleEditDialog.supplierTree.data;
        for (let i=0; i<data.length; i++){
          if (data[i].checked){
            treeCheckedList.push(data[i].id)
          }
        }
        return treeCheckedList
      }
    },
    methods: {
      searchTrans(id){
        //穿梭框右边数据获取
        this.axios.post(this.lib.config.host.system + "/system/usermgt/users/queryRoleUser/" + id).then((res) => {
          this.userform.userIdss=res.data;
          debugger;
          this.$nextTick(()=>{
            this.$refs.trans.resetCheck();
          })
        })
        .catch(function (error) {
            console.log(error);
        });
      },
      roleEdit(row) {
        this.roleEditDialog.visible = true;
        this.roleEditDialog.isRoleAdding = false;
        this.roleEditDialog.tabs.active = 'purchaser';
        this.roleEditDialog.supplierTree = {
          data: [],
          operateCheckList: {}
        };
        this.roleEditDialog.purchaserTree = {
          data: [],
          operateCheckList: {}
        };
        this.roleEditDialog.roleData = Object.assign({}, row);
        this.getRoleTreeData();
      },
      roleAdd(){
        this.roleEditDialog.supplierTree = {
          data: [],
          operateCheckList: {}
        };
        this.roleEditDialog.purchaserTree = {
          data: [],
          operateCheckList: {}
        };
        this.roleEditDialog.tabs.active = 'purchaser';
        this.roleEditDialog.roleData = {
          code: '',
          description: ''
        };
        this.roleEditDialog.visible = true;
        this.roleEditDialog.isRoleAdding = true;
        this.getRoleTreeData();
        this.$refs['roleDialogRuleForm'].resetFields();

      },
      roleDialogSupplierTreeCheck(node, isChecked) {
        if (isChecked.checkedKeys.indexOf(node.id) > -1) {
          this.parentCheck(this.$refs['supplierTree'].getNode(node.id), 'supplierTree');
          this.childCheck(node.children , 'supplierTree');
          if (this.$refs['supplierTree-' + node.id] && node.operateList && node.operateList.length > 0) {
            this.$refs['supplierTree-' + node.id].checkAll();
          }
        }
        if (isChecked.checkedKeys.indexOf(node.id) < 0 &&  node.children instanceof Array) {
          this.cancelChecked(node.children, 'supplierTree');
          if (this.$refs['supplierTree-' + node.id] && node.operateList && node.operateList.length > 0) {
            this.$refs['supplierTree-' + node.id].cancelAll();
          }
        }
      },
      roleDialogPurchaserTreeCheck(node, isChecked) {
        if (isChecked.checkedKeys.indexOf(node.id) > -1) {
          this.parentCheck(this.$refs['purchaserTree'].getNode(node.id), 'purchaserTree');
          this.childCheck(node.children , 'purchaserTree');
          if (this.$refs['purchaserTree-' + node.id] && node.operateList && node.operateList.length > 0) {
            this.$refs['purchaserTree-' + node.id].checkAll();
          }
        }
        if (isChecked.checkedKeys.indexOf(node.id) < 0 &&  node.children instanceof Array) {
          this.cancelChecked(node.children, 'purchaserTree');
          if (this.$refs['purchaserTree-' + node.id] && node.operateList && node.operateList.length > 0) {
            this.$refs['purchaserTree-' + node.id].cancelAll();
          }
        }
      },
      parentCheck(node, ref){
        if (node && node.parent) {
          this.$refs[ref].setChecked(node.parent.data.id, true);
          this.parentCheck(this.$refs[ref].getNode(node.parent.data.id), ref);
        }
      },
      childCheck(childList, ref){
        if (childList && childList.length > 0) {
//          debugger
          for (let i = 0; i < childList.length; i++) {
            this.$refs[ref].setChecked(childList[i].id, true);
            if (this.$refs[ref + '-' + childList[i].id] && childList[i].operateList && childList[i].operateList.length > 0) {
              this.$refs[ref + '-' + childList[i].id].checkAll();
            }
            this.childCheck(childList[i].children,ref);
          }
        }
      },
      cancelChecked(list, ref) {
        for (let i = 0; i < list.length; i++) {
          this.$refs[ref].setChecked(list[i].id, false);
          if (this.$refs[ref + '-' + list[i].id] && list[i].operateList && list[i].operateList.length > 0) {
            this.$refs[ref + '-' + list[i].id].cancelAll();
          }
          if (list[i].children instanceof Array && list[i].children.length > 0) {
            this.cancelChecked(list[i].children, ref);
          }
        }
      },
      getRoleTreeData() {
        this.roleEditDialog.loading = true;
        let supplierUrl = this.roleEditDialog.isRoleAdding?'/system/module/getAll/2':
          '/system/rolemgt/roles/getModulesEdit/2/'+ this.roleEditDialog.roleData.id;
        let purchaserUrl = this.roleEditDialog.isRoleAdding?'/system/module/getAll/1':
          '/system/rolemgt/roles/getModulesEdit/1/'+ this.roleEditDialog.roleData.id;
        let method = this.roleEditDialog.isRoleAdding?'get': 'post';
        this.axios[method](this.lib.config.host.system + supplierUrl).then((res)=>{
          res.data.forEach((data)=>{
            let checkList = [];
            data.operateList.forEach((item)=>{
              if (item.checked) {
                checkList.push(item.btnId)
              }
            });
            this.roleEditDialog.supplierTree.operateCheckList[data.id] = checkList
          });
          this.roleEditDialog.supplierTree.data = res.data;
        }).catch(()=> {
          Message.error({'message': '角色数据获取失败'})
        });
        this.axios[method](this.lib.config.host.system + purchaserUrl).then((res)=>{
          res.data.forEach((data)=>{
            let checkList = [];
            data.operateList.forEach((item)=>{
              if (item.checked) {
                checkList.push(item.btnId)
              }
            });
            this.roleEditDialog.purchaserTree.operateCheckList[data.id] = checkList
          });
          this.roleEditDialog.purchaserTree.data = res.data;
          this.roleEditDialog.loading = false;
        }).catch(()=> {
          Message.error({'message': '角色数据获取失败'});
          this.roleEditDialog.loading = false;
        })
      },
      supplierOperateCheckChange(data){
        this.$nextTick(()=>{
            this.roleEditDialog.supplierTree.operateCheckList[data.id] = data.operateListChecked
        })
      },
      purchaserOperateCheckChange(data) {
        this.$nextTick(()=>{
          this.roleEditDialog.purchaserTree.operateCheckList[data.id] = data.operateListChecked
        })
      },
//      supplierTreeRenderContent(h, { node, data, store }) {
//        let self = this;
//        return h(OperateCheck, {
//          props: {nodeData: data},
//          ref: 'supplierTree_' + data.id,
//          on: {
//            'check-change': self.supplierOperateCheckChange
//          }});
//      },
//      purchaserTreeRenderContent(h, { node, data, store }){
//        let self = this;
//        return h(OperateCheck, {
//          props: {nodeData: data},
//          ref: 'purchaserTree_' + data.id,
//          on: {
//            'check-change': self.purchaserOperateCheckChange
//          }
//        });
//      },
      roleCommit() {
        let purchaserCheckedNode = this.$refs.purchaserTree.getCheckedKeys();
        let supplierCheckedNode = this.$refs.supplierTree.getCheckedKeys();
        let purchaserOperateChecked = [];
        Object.values(this.roleEditDialog.purchaserTree.operateCheckList).forEach((item)=>{
          purchaserOperateChecked.push(...item)
        });
        let supplierOperateChecked = [];
        Object.values(this.roleEditDialog.supplierTree.operateCheckList).forEach((item)=>{
          supplierOperateChecked.push(...item)
        });

        let req ={
          buyerModuleId: purchaserCheckedNode.join(','),
          vendorModuleId: supplierCheckedNode.join(','),
          buyerOperateId: purchaserOperateChecked.join(','),
          vendorOperateId: supplierOperateChecked.join(','),
          code: this.roleEditDialog.roleData.code,
          description: this.roleEditDialog.roleData.description
        };
        if (!this.roleEditDialog.isRoleAdding){
          req.id = this.roleEditDialog.roleData.id;
          this.axios.post(this.lib.config.host.system + '/system/rolemgt/roles/saveOrUpdate',  qs.stringify(req)).then((res)=>{
            this.roleEditDialog.visible = false
          });
        } else {
          this.$refs['roleDialogRuleForm'].validate((valid) => {
            if (valid) {
              this.axios.post(this.lib.config.host.system + '/system/rolemgt/roles/saveOrUpdate',  qs.stringify(req)).then((res)=>{
                this.roleEditDialog.visible = false
              });
            }
          })
        }
      },
      transformToTreeFormat(array){
        let i,l,
          key = 'id',
          parentKey = 'parentId',
          childKey = 'children';

        if (array instanceof Array) {
          let r = [];
          let tmpMap = {};
          for (i=0, l=array.length; i<l; i++) {
            if (array[i]) {
              tmpMap[array[i][key]] = array[i];
            }
          }
          for (i=0, l=array.length; i<l; i++) {
            if (array[i] && tmpMap[array[i][parentKey]] && array[i][key] !== array[i][parentKey]) {
              if (!tmpMap[array[i][parentKey]][childKey])
                tmpMap[array[i][parentKey]][childKey] = [];
              tmpMap[array[i][parentKey]][childKey].push(array[i]);
            } else {
              r.push(array[i]);
            }
          }
          return r;
        } else {
          return [array];
        }
      },
      deleteRole(id) {
        //删除角色
        // this.axios.post(this.lib.config.host.system + "/system/rolemgt/roles/delete/" + id)
        //   .then((response) => {
        //     this.$refs['tableExt'].refreshTable();
        //     this.$message({
        //       type: 'success',
        //       message: '删除成功!'
        //     });
        //   }).catch((error) => {
        //   this.$message({
        //     type: 'info',
        //     message: '取消成功'
        //   });
        // });

         this.$confirm('是否删除角色?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              this.axios.post(this.lib.config.host.system + "/system/rolemgt/roles/delete/" + id)
              done();
            } else {
              done();
            }
          }
        }).then((response) => {
          this.$refs['tableExt'].refreshTable();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch((error) => {
          this.$message({
            type: 'info',
            message: '操作失败！'
          });
        });
      },
      allowRoleUser(id) {
        debugger;
        //左右选初始化弹框加载
        this.dialogAllowUserVisible = true;
        this.userform.roleId = id;
        this.searchTrans(id);
//         this.axios.post(this.lib.config.host.system + "/system/usermgt/users/query", {
//           pageNo: 1,
//           pageSize: 15
//         }).then((response) => {
//           for (var i = 0; i < response.data.rows.length; i++) {

//             this.userData.push({
//               key: response.data.rows[i].id,
//               label: '【' + response.data.rows[i].account + '】' + response.data.rows[i].name


//             });
//           }

//         })
//           .catch(function (error) {
// //            console.log(error);
//           });

//         this.axios.post(this.lib.config.host.system + "/system/usermgt/users/queryRoleUser/" + id).then((response) => {
//           debugger;
//           if (response.data.length > 0) {
//             for (var i = 0; i < response.data.length; i++) {
//               this.userform.userIdss.push(response.data[i].id);
//             }
//             // this.userIdDate.map(item => {
//             //   console.log(item);
//             // });
//           }
//         })
//           .catch(function (error) {
// //            console.log(error);
//           });
      },

      allowRole() {
        //角色保存
        if (this.userform.userIdss.length > 0) {
          for (var i = 0; i < this.userform.userIdss.length; i++) {
            this.userform.users += this.userform.userIdss[i].id + ","
          }
          this.userform.users = this.userform.users.substr(0, this.userform.users.length - 1);

//          console.log(this.userform.users);
        }
        debugger;
        this.axios.post(this.lib.config.host.system + "/system/usermgt/users/saveRoleUser", qs.stringify(this.userform))
          .then((response) => {
            debugger;
            this.dialogAllowUserVisible = false;
            this.$refs['tableExt'].refreshTable();
            this.userData = [];
            this.userform.userIdss = []
            this.userform.users = ''
          })
          .catch((error) => {
//            console.log(error);
            this.userData = [];
            this.userform.userIdss = []
            this.userform.users = ''
          });


      },
      resrRoleForm() {
        this.dialogAllowUserVisible = false;
        this.userData = [];
        this.userform.userIdss = []
      },
      renderFunc(h, option) {
        return
      <span> {option.label} </span>;
      },
    }
  }

</script>
<style>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .el-tree-node>.el-tree-node__children {
    overflow: unset;
  }
</style>
